package service

import (
	"fmt"
	"mime/multipart"
	"os"
	"path"
	"server/global"
	"server/utils"
	"strings"

	"server/utils/file"
)

// GetBinFullUrl get the full access path
func GetBinFullUrl(name string) string {
	return global.CONFIG.Upload.Url + "/" + GetBinPath() + "/" + name
}

// GetBinName get image name
func GetBinName(name string) string {
	ext := path.Ext(name)
	fileName := strings.TrimSuffix(name, ext)
	fileName = utils.EncodeMD5(fileName)

	return fileName + ext
}

// GetBinPath get save path
func GetBinPath() string {
	return global.CONFIG.Upload.BinPath
}

// GetBinFullPath get full save path
func GetBinFullPath() string {
	return GetBinPath()
}

// CheckBinExt check image file ext
func CheckBinExt(fileName string) bool {
	ext := file.GetExt(fileName)
	for _, allowExt := range global.CONFIG.Upload.BinAllowExts {
		if strings.ToUpper(allowExt) == strings.ToUpper(ext) {
			return true
		}
	}

	return false
}

// CheckBinSize check image size
func CheckBinSize(f multipart.File) bool {
	size, err := file.GetSize(f)
	if err != nil {
		return false
	}

	return size <= global.CONFIG.Upload.BinMaxsize*1024*1024
}

// CheckBin check if the file exists
func CheckBin(src string) error {
	dir, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("os.Getwd err: %v", err)
	}

	err = file.IsNotExistMkDir(dir + "/" + src)
	if err != nil {
		return fmt.Errorf("file.IsNotExistMkDir err: %v", err)
	}

	perm := file.CheckPermission(src)
	if perm == true {
		return fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
	}

	return nil
}
